package com.fingard.dsp.bank.directbank.gzelink01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class GZELINK01BatPayRec extends GZELINK01Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return d_BatPayRec(p_req1988);
	}

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return d_BatPayRec(p_req9188);
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return d_QryBatPayRec(p_req9198);
	}
	
	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqBat.ownAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath) || !FileHelper.existFile(actItem.oppCertFilePath)) {
				retAts.respCode = "0";
				if (actItem == null) {
					retAts.respInfo = "未找到账号[" + p_reqBat.ownAct + "]商户配置信息";
				} else {
					retAts.respInfo = "账号[" + p_reqBat.ownAct + "]证书文件不存在";
				}
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = FailCode.E9981;
				retAts.writeRetToATS();
				return retAts;
			}
			
			GZELINK01Header bankHeader = new GZELINK01Header();
			
			if ("9188".equals(p_reqBat.reqHeader.transType)) {
				bankHeader.transCode = "100001";
				bankHeader.busiCode = getBankConfig().getMapValueByKey("BatRecBusiCode", p_reqBat.useType);
			}else if ("1988".equals(p_reqBat.reqHeader.transType)) {
				bankHeader.transCode = "100002";
				bankHeader.busiCode = getBankConfig().getMapValueByKey("BatPayBusiCode", p_reqBat.useType);
			}
			
			bankHeader.reqSeqNo = p_reqBat.reqBatchNO;
			bankHeader.totalNum = p_reqBat.totalNum;
			bankHeader.totalAmt = p_reqBat.totalAmt;
			
			StringBuilder reqMsg = new StringBuilder();
			reqMsg = writeBatPayRecSubmitMsg(reqMsg, actItem, bankHeader);
			
			while(p_reqBat.readRecord()) {
				reqMsg.append("<TRANS_DETAIL>");
				reqMsg.append("<SN>" + p_reqBat.readedDetail.askNumber + "</SN>");
				reqMsg.append("<E_USER_CODE>" + actItem.merchantId + "</E_USER_CODE>");
				
				if ("1".equals(p_reqBat.readedDetail.cardType)) {
					reqMsg.append("<ACCOUNT_TYPE>01</ACCOUNT_TYPE>");// 存折
				} else if ("2".equals(p_reqBat.readedDetail.cardType)) {
					reqMsg.append("<ACCOUNT_TYPE>00</ACCOUNT_TYPE>");// 银行卡
				}
				
				reqMsg.append("<PROVINCE>" + p_reqBat.readedDetail.getOppProvinceAndCity2()[0]+ "</PROVINCE>");
				reqMsg.append("<CITY>" + p_reqBat.readedDetail.getOppProvinceAndCity2()[1]+ "</CITY>");
				reqMsg.append("<BANK_NAME>" + p_reqBat.readedDetail.cnapsName + "</BANK_NAME>");
				
				if ("1".equals(p_reqBat.readedDetail.isPrivate)) {
					reqMsg.append("<ACCOUNT_PROP>0</ACCOUNT_PROP>");// 对私
				} else if ("2".equals(p_reqBat.readedDetail.cardType)) {
					reqMsg.append("<ACCOUNT_PROP>1</ACCOUNT_PROP>");// 公司
				}
				
				reqMsg.append("<AMOUNT>" + StringHelper.amountMultiply100(p_reqBat.readedDetail.payAmount) + "</AMOUNT>");
				reqMsg.append("<CURRENCY></CURRENCY>");
				reqMsg.append("<PROTOCOL></PROTOCOL>");
				reqMsg.append("<PROTOCOL_USERID></PROTOCOL_USERID>");
				reqMsg.append("<ID_TYPE>" + convertCertTypeToBank(p_reqBat.readedDetail.certType) + "</ID_TYPE>");
				reqMsg.append("<ID>" + p_reqBat.readedDetail.certNum + "</ID>");
				reqMsg.append("<TEL>" + p_reqBat.readedDetail.cellPhone + "</TEL>");
				reqMsg.append("<RECKON_ACCOUNT></RECKON_ACCOUNT>");
				reqMsg.append("<CUST_USERID>" + p_reqBat.readedDetail.askNumber + "</CUST_USERID>");
				reqMsg.append("<REMARK></REMARK>");
				
				boolean usebatPayReserve = getBankConfig().getValueAsBool("usebatPayReserve");
				if (usebatPayReserve) {
					String reserve1 = getBankConfig().getMapValueByKey("reserveKeyMapping", "RESERVE1");
					if (StringHelper.hasAnyChar(reserve1)) {
						reserve1 = p_reqBat.readedDetail.srcXElement.getSingleText(reserve1);
					} else {
						reserve1 = "";
					}
					reqMsg.append("<RESERVE1>" + reserve1 + "</RESERVE1>");
					
					String reserve2 = getBankConfig().getMapValueByKey("reserveKeyMapping", "RESERVE2");
					if (StringHelper.hasAnyChar(reserve1)) {
						reserve2 = p_reqBat.readedDetail.srcXElement.getSingleText(reserve2);
					} else {
						reserve2 = "";
					}
					reqMsg.append("<RESERVE2>" + reserve2 + "</RESERVE2>");
					
					String reserve3 = getBankConfig().getMapValueByKey("reserveKeyMapping", "RESERVE3");
					if (StringHelper.hasAnyChar(reserve3)) {
						reserve3 = p_reqBat.readedDetail.srcXElement.getSingleText(reserve3);
					} else {
						reserve3 = "";
					}
					reqMsg.append("<RESERVE3>" + reserve3 + "</RESERVE3>");
					
					String reserve4 = getBankConfig().getMapValueByKey("reserveKeyMapping", "RESERVE4");
					if (StringHelper.hasAnyChar(reserve4)) {
						reserve4 = p_reqBat.readedDetail.srcXElement.getSingleText(reserve4);
					} else {
						reserve4 = "";
					}
					reqMsg.append("<RESERVE4>" + reserve4 + "</RESERVE4>");
				} else {
					reqMsg.append("<RESERVE1></RESERVE1>");
					reqMsg.append("<RESERVE2></RESERVE2>");
					reqMsg.append("<RESERVE3></RESERVE3>");
					reqMsg.append("<RESERVE4></RESERVE4>");
				}
				reqMsg.append("<ELE_BANKNO></ELE_BANKNO>");
				reqMsg.append("<ABS></ABS>");
				reqMsg.append("<PS></PS>");
				reqMsg.append("<USE></USE>");
				reqMsg.append("<CRE_VAL_DATE></CRE_VAL_DATE>");
				reqMsg.append("<CRE_CVN2></CRE_CVN2>");
				reqMsg.append("<ACC_PASS></ACC_PASS>");
				
				String payRecBankCode = "";
				if ("1988".equals(p_reqBat.reqHeader.transType)) {
					payRecBankCode = p_reqBat.readedDetail.recBankCode;
					
					reqMsg.append("<ACCOUNT_NO>" + p_reqBat.readedDetail.recAct + "</ACCOUNT_NO>");
					reqMsg.append("<ACCOUNT_NAME>" + p_reqBat.readedDetail.recName + "</ACCOUNT_NAME>");
				} else {
					payRecBankCode = p_reqBat.readedDetail.payBankCode;
					reqMsg.append("<ACCOUNT_NO>" + p_reqBat.readedDetail.payAct + "</ACCOUNT_NO>");
					reqMsg.append("<ACCOUNT_NAME>" + p_reqBat.readedDetail.payName + "</ACCOUNT_NAME>");
				}
				
				String bankCode = getBankConfig().getMapValueByKey("BankCodeMapping", payRecBankCode);
				reqMsg.append("<BANK_CODE>" + bankCode + "</BANK_CODE>");
				reqMsg.append("</TRANS_DETAIL>");
			}
			
			reqMsg.append("</TRANS_DETAILS>");
			reqMsg.append("</BODY>");
			reqMsg.append("</GZELINK>");
			System.out.println(reqMsg.toString());
			
			// 签名
			String signData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
			
			WriteBankLogLn2("待签名数据:\r\n" + signData);
			
			String signature = signMsg(signData, actItem);
			
			String reqData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "<SIGNED_MSG>" + signature + "</SIGNED_MSG>");
			
			WriteBankLogLn2("发送广银联请求报文:\r\n" + reqData);
			
			String[] tmpRetStr = sendDataToGZE(reqData, bankFront.getUrl("generalRecPay"));
			if(tmpRetStr[0].length() == 0) {
				WriteBankLogStep3(tmpRetStr[1]);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
				
				if (tmpBkReader != null) {
					String tmpRespCode = tmpBkReader.getFirstText("/GZELINK/INFO/RET_CODE");
					
					retAts.respCode = "0";
					retAts.respInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");
					
					String reqSeqID = tmpBkReader.getFirstText("/GZELINK/INFO/REQ_SN");
					if (StringHelper.isNullOrEmpty(reqSeqID)) {
						reqSeqID = p_reqBat.reqBatchNO;
					}
					retAts.reqSeqID = reqSeqID;
					
					retAts.transState = tmpRespCode;
					retAts.payInfoCode = tmpRespCode;
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else {
				retAts.respCode = "-1"; 
				retAts.respInfo = tmpRetStr[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			
			WriteBankLogLn(ex);
		}
		
		if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_reqBat.reqBatchNO;
		}
		
		retAts.writeRetToATS();
		return retAts;
	}
	
	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
		retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQryBat.ownAct,"");
            if (actItem != null ) {
                GZELINK01Header bankHeader = new GZELINK01Header();
                bankHeader.transCode = "200001";
                bankHeader.reqSeqNo = p_reqQryBat.reqBatchNO;

                StringBuilder reqMsg = new StringBuilder();
                reqMsg = writePayRecQueryMsg(reqMsg, actItem, bankHeader, p_reqQryBat.reqBatchNO);

                // 签名
                String signData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");

                WriteBankLogLn2("待签名数据:\r\n" + signData);

                String signature = signMsg(signData, actItem);

                // 请求数据
                String reqData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "<SIGNED_MSG>" + signature + "</SIGNED_MSG>");

                WriteBankLogLn2("发送广银联请求报文:\r\n" + reqData);

                String[] tmpRetStr = sendDataToGZE(reqData, bankFront.getUrl("generalRecPay"));

                if(tmpRetStr[0].length() == 0) {
                    WriteBankLogStep3(tmpRetStr[1]);
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");

                        String tmpRespCode = tmpBkReader.getFirstText("/GZELINK/INFO/RET_CODE");
                        if ("0000".equals(tmpRespCode) || "0001".equals(tmpRespCode) || "0002".equals(tmpRespCode) || "1002".equals(tmpRespCode) || "2000".equals(tmpRespCode)
								|| "2001".equals(tmpRespCode) || "2002".equals(tmpRespCode) || "2003".equals(tmpRespCode) || "2004".equals(tmpRespCode) || "2005".equals(tmpRespCode)
								|| "2006".equals(tmpRespCode) || "2007".equals(tmpRespCode)) {
							retAts.transState = tmpRespCode;
							retAts.payInfoCode = tmpRespCode;
                        	if ("0001".equals(tmpRespCode) || "0002".equals(tmpRespCode) || "1002".equals(tmpRespCode) || "2002".equals(tmpRespCode) || "2004".equals(tmpRespCode) || "2006".equals(tmpRespCode) || "2007".equals(tmpRespCode)) {
								retAts.writeAfterDetail();
								return retAts;
							}
							while(tmpBkReader.read("/GZELINK/BODY/RET_DETAILS/RET_DETAIL")){
								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

								if(p_reqQryBat.reqHeader.transType.equals("1998")){
									tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("ACCOUNT");
									tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("ACCOUNT_NAME");
								} else if(p_reqQryBat.reqHeader.transType.equals("9198")){
									tmpRetDetail.payAct = tmpBkReader.readedXElement.getSingleText("ACCOUNT");
									tmpRetDetail.payName = tmpBkReader.readedXElement.getSingleText("ACCOUNT_NAME");
								}

								tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("CUST_USERID");
								tmpRetDetail.payAmount = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("AMOUNT"));
								tmpRetDetail.memo = tmpBkReader.readedXElement.getSingleText("REMARK");

								String tmpRetCode = tmpBkReader.readedXElement.getSingleText("RET_CODE");
								String tmpErrMsg = tmpBkReader.readedXElement.getSingleText("ERR_MSG");
								if (StringHelper.hasAnyChar(tmpErrMsg)) {
									tmpRetDetail.memo = tmpErrMsg;
								}

								tmpRetDetail.result = StringHelper.joinNotEmpty("+", tmpRespCode, tmpRetCode);
								tmpRetDetail.payInfoCode = tmpRetCode;
								if ("3999".equals(tmpRetCode)) {
									tmpRetDetail.payInfoCode = tmpErrMsg;
									tmpRetDetail.memo = tmpErrMsg;
								}

								retAts.writeRetDetail(tmpRetDetail);
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");
						}
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpRetStr[1];
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_reqQryBat.ownAct + "]商户配置信息!";
            }
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}
}
